package frog.lazy.framework.core.mybatis.handler;

import cn.hutool.core.date.DateUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

@Component
@MappedTypes({LocalDateTime.class, LocalDate.class})
@MappedJdbcTypes({JdbcType.DATE, JdbcType.TIMESTAMP})
public class DateDefaultTypeHandler extends BaseTypeHandler<LocalDateTime> {
    private Date defaultDate = new Date(0);
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, LocalDateTime o, JdbcType jdbcType) {
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return sqlDateToLocalDate(resultSet.getDate(columnName));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return sqlDateToLocalDate(resultSet.getDate(i));
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return sqlDateToLocalDate(callableStatement.getDate(i));
    }

    private LocalDateTime sqlDateToLocalDate(java.sql.Date sqlDate) {
        if(sqlDate != null){
            Date rs = new Date(sqlDate.getTime());
            if(rs.after(defaultDate)){
                return DateUtil.toLocalDateTime(rs);
            }
        }
        return null;
    }
}
